#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ford UK车型配置器链接爬取脚本
从 https://www.ford.co.uk/cars 获取所有车型的配置器链接
"""

import sys
import os
import json
import time
from datetime import datetime

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from src.base import BaseWebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException


class FordCarsAnalyzer:
    """Ford UK所有车型分析器"""
    
    def __init__(self):
        self.driver_manager = BaseWebDriver()
        self.driver = None
        self.wait = None
        self.results = {
            "analysis_date": datetime.now().isoformat(),
            "source_url": "https://www.ford.co.uk/cars",
            "discovered_cars": [],
            "configurator_links": {},
            "errors": []
        }
    
    def setup_and_navigate(self):
        """初始化并导航到Ford cars页面"""
        try:
            self.driver_manager.setup_driver()
            self.driver = self.driver_manager.driver
            self.wait = WebDriverWait(self.driver, 15)
            
            target_url = "https://www.ford.co.uk/cars"
            print(f"🌐 正在访问Ford UK cars页面: {target_url}")
            
            self.driver.get(target_url)
            time.sleep(5)
            
            self.handle_cookies()
            print(f"✅ 页面加载成功")
            return True
            
        except Exception as e:
            error_msg = f"初始化失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return False
    
    def handle_cookies(self):
        """处理Cookie弹窗"""
        try:
            time.sleep(3)
            cookie_selectors = [
                "#onetrust-accept-btn-handler",
                "button[id*='accept']",
                "button[class*='accept']",
                ".ot-accept-all-handler"
            ]
            
            for selector in cookie_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for element in elements:
                        if element.is_displayed():
                            self.driver.execute_script("arguments[0].click();", element)
                            print(f"✅ 处理了Cookie弹窗")
                            time.sleep(2)
                            return
                except:
                    continue
        except Exception as e:
            print(f"⚠️ Cookie处理异常: {e}")
    
    def find_all_cars(self):
        """找出所有Ford车型"""
        try:
            print("\n🚗 开始搜索Ford车型...")
            
            # 等待页面加载完成
            time.sleep(5)
            
            # 滚动页面确保所有内容加载
            self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(3)
            self.driver.execute_script("window.scrollTo(0, 0);")
            time.sleep(2)
            
            cars_found = []
            
            # 策略1: 查找车型卡片
            card_selectors = [
                "div[class*='car-card']",
                "div[class*='vehicle-card']", 
                "div[class*='product-card']",
                ".card",
                "div[class*='tile']"
            ]
            
            for selector in card_selectors:
                try:
                    cards = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    print(f"  🔍 选择器 '{selector}' 找到 {len(cards)} 个卡片")
                    
                    for card in cards:
                        try:
                            car_info = self.extract_car_info_from_card(card)
                            if car_info and car_info not in cars_found:
                                cars_found.append(car_info)
                        except:
                            continue
                            
                except Exception as e:
                    print(f"    ❌ 选择器 '{selector}' 失败: {e}")
                    continue
            
            # 策略2: 查找包含车型名称的链接
            print("\n  🔗 搜索车型链接...")
            
            # 常见Ford车型名称
            ford_models = [
                'focus', 'fiesta', 'kuga', 'puma', 'mustang', 'ranger', 
                'transit', 'mondeo', 'galaxy', 'edge', 'ecosport', 
                'tourneo', 'bronco', 'explorer', 'maverick'
            ]
            
            links = self.driver.find_elements(By.TAG_NAME, "a")
            print(f"  找到 {len(links)} 个链接，开始分析...")
            
            for link in links:
                try:
                    href = link.get_attribute('href') or ''
                    text = link.text.strip().lower()
                    
                    # 检查链接是否包含车型名称
                    for model in ford_models:
                        if (model in href.lower() or model in text) and 'ford.co.uk' in href:
                            car_info = {
                                'name': model.title(),
                                'display_name': link.text.strip() if link.text.strip() else model.title(),
                                'url': href,
                                'source': 'link_analysis'
                            }
                            
                            # 检查重复
                            if not any(car['name'].lower() == model for car in cars_found):
                                cars_found.append(car_info)
                                print(f"    ✅ 发现车型: {model.title()} - {href}")
                            
                except Exception as e:
                    continue
            
            # 去重和清理
            unique_cars = []
            seen_names = set()
            
            for car in cars_found:
                name_key = car['name'].lower()
                if name_key not in seen_names:
                    seen_names.add(name_key)
                    unique_cars.append(car)
            
            self.results["discovered_cars"] = unique_cars
            
            print(f"\n✅ 总共发现 {len(unique_cars)} 个唯一车型:")
            for car in unique_cars:
                print(f"  - {car['name']}: {car.get('url', '无链接')}")
            
            return unique_cars
            
        except Exception as e:
            error_msg = f"搜索车型失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return []
    
    def extract_car_info_from_card(self, card):
        """从车型卡片中提取信息"""
        try:
            # 尝试获取车型名称
            name_selectors = ['h1', 'h2', 'h3', 'h4', '.title', '.name', '.model']
            car_name = None
            
            for selector in name_selectors:
                try:
                    name_element = card.find_element(By.CSS_SELECTOR, selector)
                    potential_name = name_element.text.strip()
                    if potential_name and len(potential_name) < 50:  # 避免获取长描述
                        car_name = potential_name
                        break
                except:
                    continue
            
            if not car_name:
                return None
            
            # 尝试获取链接
            car_url = None
            try:
                # 检查卡片本身是否是链接
                if card.tag_name == 'a':
                    car_url = card.get_attribute('href')
                else:
                    # 查找卡片内的链接
                    link_element = card.find_element(By.TAG_NAME, 'a')
                    car_url = link_element.get_attribute('href')
            except:
                pass
            
            return {
                'name': car_name,
                'display_name': car_name,
                'url': car_url,
                'source': 'card_extraction'
            }
            
        except Exception as e:
            return None
    
    def find_configurator_links(self, cars):
        """为每个车型寻找配置器链接"""
        try:
            print(f"\n🔧 开始为 {len(cars)} 个车型寻找配置器链接...")
            
            configurator_links = {}
            
            for car in cars:
                car_name = car['name']
                car_url = car.get('url')
                
                print(f"\n  🚗 处理车型: {car_name}")
                
                if not car_url or 'ford.co.uk' not in car_url:
                    print(f"    ⚠️ 无有效链接，跳过")
                    continue
                
                try:
                    # 访问车型页面
                    print(f"    🌐 访问: {car_url}")
                    self.driver.get(car_url)
                    time.sleep(3)
                    
                    # 查找配置器链接
                    configurator_link = self.find_configurator_on_page(car_name)
                    
                    if configurator_link:
                        configurator_links[car_name.lower()] = {
                            'name': car_name,
                            'car_page': car_url,
                            'configurator_url': configurator_link,
                            'found_date': datetime.now().isoformat()
                        }
                        print(f"    ✅ 找到配置器: {configurator_link}")
                    else:
                        print(f"    ❌ 未找到配置器链接")
                    
                    # 适当延迟
                    time.sleep(2)
                    
                except Exception as e:
                    error_msg = f"{car_name}: 处理失败 - {e}"
                    print(f"    ❌ {error_msg}")
                    self.results["errors"].append(error_msg)
                    continue
            
            self.results["configurator_links"] = configurator_links
            
            print(f"\n📈 配置器链接搜索完成:")
            print(f"  成功找到: {len(configurator_links)} 个")
            print(f"  失败: {len(cars) - len(configurator_links)} 个")
            
            return configurator_links
            
        except Exception as e:
            error_msg = f"寻找配置器链接失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return {}
    
    def find_configurator_on_page(self, car_name):
        """在车型页面上查找配置器链接"""
        try:
            # 常见的配置器链接文本和属性
            configurator_keywords = [
                'build', 'configure', 'customise', 'customize', 'design',
                'build your', 'configure your', 'start building',
                'ngc2', 'configurator'
            ]
            
            # 查找所有链接
            links = self.driver.find_elements(By.TAG_NAME, 'a')
            
            for link in links:
                try:
                    href = link.get_attribute('href') or ''
                    text = link.text.strip().lower()
                    
                    # 检查是否是配置器链接
                    for keyword in configurator_keywords:
                        if (keyword in text or keyword in href.lower()) and 'ford.co.uk' in href:
                            # 进一步验证是否是真正的配置器
                            if ('build' in href or 'ngc2' in href or 'configure' in href):
                                return href
                    
                except Exception as e:
                    continue
            
            # 如果没找到，尝试查找按钮
            buttons = self.driver.find_elements(By.TAG_NAME, 'button')
            for button in buttons:
                try:
                    text = button.text.strip().lower()
                    onclick = button.get_attribute('onclick') or ''
                    
                    for keyword in configurator_keywords:
                        if keyword in text or keyword in onclick:
                            # 尝试点击按钮看是否跳转到配置器
                            # 这里暂时不实现自动点击，避免破坏页面状态
                            pass
                            
                except Exception as e:
                    continue
            
            return None
            
        except Exception as e:
            print(f"    ❌ 页面分析失败: {e}")
            return None
    
    def update_config_file(self, configurator_links):
        """更新fetchNgc2.json配置文件"""
        try:
            print(f"\n💾 更新配置文件...")
            
            # 读取现有配置
            config_file = 'fetchNgc2.json'
            if os.path.exists(config_file):
                with open(config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
            else:
                config = {}
            
            # 添加新的车型配置
            if 'all_models' not in config:
                config['all_models'] = {}
            
            config['all_models'].update(configurator_links)
            
            # 添加发现信息
            config['discovery_info'] = {
                'last_updated': datetime.now().isoformat(),
                'source': 'https://www.ford.co.uk/cars',
                'total_models_found': len(configurator_links),
                'models': list(configurator_links.keys())
            }
            
            # 保存更新后的配置
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=4, ensure_ascii=False)
            
            print(f"✅ 配置文件已更新: {config_file}")
            print(f"  新增车型: {len(configurator_links)} 个")
            
            return True
            
        except Exception as e:
            error_msg = f"更新配置文件失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return False
    
    def save_results(self):
        """保存分析结果"""
        try:
            output_file = "./release/ford_cars_analysis.json"
            os.makedirs(os.path.dirname(output_file), exist_ok=True)
            
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(self.results, f, ensure_ascii=False, indent=2)
            
            print(f"💾 分析结果已保存到: {output_file}")
            
        except Exception as e:
            print(f"❌ 保存结果失败: {e}")
    
    def cleanup(self):
        """清理资源"""
        try:
            if self.driver_manager:
                self.driver_manager.cleanup()
        except Exception as e:
            print(f"⚠️ 清理资源时出错: {e}")
    
    def run_analysis(self):
        """运行完整分析"""
        try:
            print("🔍 Ford UK车型配置器链接分析开始...")
            print("=" * 60)
            
            if not self.setup_and_navigate():
                return False
            
            # 1. 查找所有车型
            cars = self.find_all_cars()
            
            if not cars:
                print("❌ 未发现任何车型")
                return False
            
            # 2. 为每个车型寻找配置器链接
            configurator_links = self.find_configurator_links(cars)
            
            # 3. 更新配置文件
            if configurator_links:
                self.update_config_file(configurator_links)
            
            # 4. 保存结果
            self.save_results()
            
            print("\n🎉 分析完成！")
            return True
            
        except Exception as e:
            error_msg = f"分析失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return False
        
        finally:
            self.cleanup()


def main():
    """主函数"""
    analyzer = FordCarsAnalyzer()
    success = analyzer.run_analysis()
    
    if success:
        print("\n📊 分析结果摘要:")
        print(f"  发现车型: {len(analyzer.results['discovered_cars'])} 个")
        print(f"  配置器链接: {len(analyzer.results['configurator_links'])} 个")
        print(f"  错误数量: {len(analyzer.results['errors'])}")
        
        if analyzer.results['configurator_links']:
            print("\n🔧 找到的配置器:")
            for name, info in analyzer.results['configurator_links'].items():
                print(f"  - {info['name']}: {info['configurator_url']}")
    else:
        print("❌ 分析失败")


if __name__ == "__main__":
    main()
